﻿using System;
using System.Drawing;
using System.Windows.Forms;

namespace sy4_6
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        // 窗体载入事件：初始化滚动条和图片
        private void Form1_Load(object sender, EventArgs e)
        {
            initHScrollBar();
            initPicture();
        }

        // 初始化水平滚动条
        private void initHScrollBar()
        {
            hScrollBar1.Minimum = 0;
            hScrollBar1.Maximum = 119;  // 划块占用20宽度，确保缩放比例可到100%
            hScrollBar1.SmallChange = 5;
            hScrollBar1.LargeChange = 20;
            hScrollBar1.Value = 100;    // 初始缩放比例为100%
            hScrollBar1.Dock = DockStyle.Bottom;
        }

        // 初始化图片框
        private void initPicture()
        {
            pictureBox1.Image = Image.FromFile;
            pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
            pictureBox1.Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top | AnchorStyles.Bottom;
            zoomPic(hScrollBar1.Value);
        }

        // 图片缩放并居中方法
        private void zoomPic(int ratio)
        {
            float ratio_f = (float)ratio / 100;
            // 计算图片框宽高（基于窗体客户区大小和缩放比例）
            pictureBox1.Width = (int)(this.ClientSize.Width * ratio_f);
            pictureBox1.Height = (int)((this.ClientSize.Height - hScrollBar1.Height) * ratio_f);
            // 计算图片框位置，使其居中
            pictureBox1.Left = (this.ClientSize.Width - pictureBox1.Width) / 2;
            pictureBox1.Top = (this.ClientSize.Height - hScrollBar1.Height - pictureBox1.Height) / 2;
            // 窗体标题显示当前缩放比例
            this.Text = "图像浏览器 " + ratio.ToString() + "%";
        }

        // 滚动条滚动事件：触发图片缩放
        private void hScrollBar1_Scroll(object sender, ScrollEventArgs e)
        {
            zoomPic(hScrollBar1.Value);
        }
    }
}